package com.kexin.common.controller;


import com.kexin.common.exception.WebException;
import com.kexin.common.numeration.ExceptionEnum;
import com.kexin.common.utils.ErrorResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author chen
 * @date 2020/3/31
 */

@Api(tags = "不可捕获异常处理控制类")
@Controller
public class NoCatchExceptionController implements ErrorController {

    Logger log = LoggerFactory.getLogger(NoCatchExceptionController.class);

    @Autowired
    private ErrorAttributes errorAttributes;

    public String getErrorPath() {
        return "/error";
    }

    @ApiOperation("异常跳转地址")
    @RequestMapping(value = {"/error"})
    public void error(HttpServletRequest request, HttpServletResponse response) {
        ServletWebRequest  servletWebRequest = new ServletWebRequest(request);
        Map<String,Object> errorAttributeMap = errorAttributes.getErrorAttributes(servletWebRequest, true);
        request.setAttribute("path",errorAttributeMap.get("path"));
        Object path = errorAttributeMap.get("path");
        if (path!=null){
            path.toString().startsWith("/webjars");
            return;
        }
        if (response.getStatus() == 404) {
            ErrorResponseUtils.handler(log,request,response,new WebException(ExceptionEnum.ERROR_NO_FOUND));
        } else if (response.getStatus() == 400) {
            ErrorResponseUtils.handler(log,request,response,new WebException(ExceptionEnum.ERROR_MISS_PARAM));
        } else if (response.getStatus() == 500) {
            ErrorResponseUtils.handler(log,request,response,new WebException(ExceptionEnum.ERROR_INTERNAL_SERVER));
        }else {
            ErrorResponseUtils.handler(log,request,response,new WebException(ExceptionEnum.ERROR_INTERNAL_SERVER.getCode(),"未知异常！"));
        }
    }
}